package data

import (
	"crawler_translation/utils"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"go.uber.org/zap"
)

type MysqlDB struct {
	Conn *sqlx.DB
}

var MConn *MysqlDB

func NewMysql() (err error) {
	// root:root@tcp(127.0.0.1:3306)/test
	user := "aleocn"
	pwd := "n8kack3yKp3mMktE"
	addr := "127.0.0.1"
	port := 3306
	db := "aleocn"
	database, err := sqlx.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, pwd, addr, port, db))
	if err != nil {
		fmt.Println("open mysql failed,", err)
		return err
	}

	MConn = &MysqlDB{
		Conn: database,
	}

	return nil
}

// GetMenuList 获取menu列表
func (d *MysqlDB) GetMenuList() (menu []Menu, err error) {
	err = d.Conn.Select(&menu, "SELECT * FROM menu")
	if err != nil {
		utils.Logger.Error("db select failed", zap.String("err", err.Error()))
	}
	return
}

// UpdateMenu 修改menu的hash
func (d MysqlDB) UpdateMenu(hash string, id int) error {
	res, err := d.Conn.Exec("UPDATE menu SET hash=? WHERE id=?", hash, id)
	if err != nil {
		utils.Logger.Error("db update failed", zap.String("err", err.Error()))
		return err
	}
	_, err = res.RowsAffected()
	if err != nil {
		utils.Logger.Error("db update failed", zap.String("err", err.Error()))
		return err
	}

	return nil
}

// 存入数据库
func (d *MysqlDB) StoreDocs(docs Docs, id int) error {
	// 查询是否存在
	var _docs Docs
	err := d.Conn.Get(&_docs, fmt.Sprintf("SELECT id,title,keyword,description,content,path FROM docs WHERE id = %d", id))

	// 不存在插入
	if err != nil {
		utils.Logger.Error("db get failed", zap.String("err", err.Error()))
		_, err = d.Conn.Exec("insert into docs(id, title, keyword, description, content, path)values(?, ?, ?, ?, ?, ?)",
			docs.Id, docs.Title, docs.Keyword, docs.Description, docs.Content, docs.Path)
		if err != nil {
			utils.Logger.Error("db insert failed", zap.String("err", err.Error()))
		}
	} else {
		res, err := d.Conn.Exec("UPDATE docs SET title=?, keyword=?, description=?, content=?, path=? WHERE id=?",
			docs.Title, docs.Keyword, docs.Description, docs.Content, docs.Path, id)
		if err != nil {
			utils.Logger.Error("db update failed", zap.String("err", err.Error()))
			return err
		}
		_, err = res.RowsAffected()
		if err != nil {
			utils.Logger.Error("db update failed", zap.String("err", err.Error()))
			return err
		}
	}

	return nil
}
